<template>
  <div>
    <el-drawer
      :title="form.id ? '编辑题目' : '新增题目'"
      :visible.sync="drawer"
      :direction="direction"
      :before-close="handleClose"
      size="750px"
    >
      <div>
        <el-form
          size="small"
          ref="form"
          :model="form"
          :rules="rules"
          v-loading="loading"
          label-width="130px"
          class="demo-ruleForm"
        >
          <el-form-item label="选择条件：" prop="conditions">
            <el-select
              filterable
              v-model="form.conditions"
              placeholder="请选择条件"
              style="width: 400px"
              clearable
              @change="getSecondaryQuestionList"
            >
              <el-option
                v-for="item in ProductDimensionList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            prop="metaId"
            v-if="
              form.conditionsType === 'OP_EQUAL' ||
                form.conditionsType === 'OP_SCOPE'
            "
          >
            <el-select
              @change="selectChild"
              filterable
              v-model="form.metaId"
              placeholder=""
              style="width: 400px"
              clearable
            >
              <el-option
                v-for="item in lsl6List"
                :key="item.id"
                :label="item.label"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="题目：" prop="label">
            <el-input
              placeholder="请输入题目"
              clearable
              style="width: 400px"
              maxlength="30"
              v-model="form.label"
            ></el-input>
          </el-form-item>
          <el-form-item label="问卷类型：" prop="type">
            <el-radio-group v-model="form.type">
              <!--              <el-radio :label="1">填空</el-radio>-->
              <el-radio :label="2">单选</el-radio>
              <el-radio :label="3">多选</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="产品类型：" prop="matchType">
            <el-checkbox-group v-model="form.matchType">
              <el-checkbox
                v-for="item in matchTypeList"
                :key="item.value"
                :label="item.value"
                >{{ item.label }}</el-checkbox
              >
            </el-checkbox-group>
          </el-form-item>

          <el-form-item label="是否必填：" prop="must">
            <el-radio-group v-model="form.must">
              <el-radio :label="1">必填</el-radio>
              <!--              <el-radio :label="0">选填</el-radio>-->
            </el-radio-group>
          </el-form-item>

          <!--          <el-form-item label="是否主问题：" prop="firstShow">-->
          <!--            <el-radio-group v-model="form.firstShow">-->
          <!--              <el-radio :label="true">是</el-radio>-->
          <!--              <el-radio :label="false">否</el-radio>-->
          <!--            </el-radio-group>-->
          <!--          </el-form-item>-->

          <div v-for="(item, index) in form.options" :key="index">
            <el-form-item
              :label="`选项${index + 1}的名称：`"
              v-if="form.type == 2 || form.type == 3"
              :prop="'options.' + index + '.label'"
              :rules="{
                required: true,
                message: `选项${index + 1}的名称不能为空`,
                trigger: 'blur'
              }"
            >
              <div style="display: flex; align-items: center">
                <el-input
                  :placeholder="`请输入${index + 1}的选项名称`"
                  clearable
                  style="width: 400px"
                  v-model="item.label"
                ></el-input>
                <div style="margin-left: 10px">
                  <el-button
                    size="mini"
                    type="danger"
                    @click="form.options.splice(index, 1)"
                    v-if="index !== 0"
                  >
                    删除</el-button
                  >
                  <el-button
                    size="mini"
                    type="primary"
                    @click="addQuesTionItem(item, index)"
                    v-if="index == 0"
                  >
                    添加</el-button
                  >
                  <el-button size="mini" @click="addChildQuestion(index)"
                    >关联问题</el-button
                  >
                </div>
              </div>
            </el-form-item>

            <el-form-item
              v-if="
                form.conditionsType !== 'OP_EQUAL' &&
                  form.conditionsType !== 'OP_SCOPE' &&
                  (form.type == 2 || form.type == 3)
              "
              :label="`${index + 1}的选项值：`"
              :prop="'options.' + index + '.value'"
              :rules="{
                required: true,
                message: `选项${index + 1}的选项值不能为空`,
                trigger: 'blur'
              }"
            >
              <el-input
                :placeholder="`请输入${index + 1}的选项值`"
                clearable
                style="width: 400px"
                v-model="item.value"
              ></el-input>
            </el-form-item>
            <el-form-item
              v-if="
                (form.conditionsType == 'OP_EQUAL' ||
                  form.conditionsType == 'OP_SCOPE') &&
                  (form.type == 2 || form.type == 3) &&
                  form.metaId
              "
            >
              <div
                v-for="(v, idx1) in item.value"
                :key="idx1"
                style="margin-top: 5px"
              >
                <span
                  ><el-input
                    size="mini"
                    :disabled="v.leftOp == 'NO'"
                    v-model="v.leftValue"
                    style="width: 100px"
                  ></el-input
                ></span>
                <span
                  ><el-select
                    size="mini"
                    :placeholder="``"
                    @change="changeLeftOp($event, index, idx1)"
                    v-model="v.leftOp"
                    style="width: 60px"
                  >
                    <el-option
                      v-for="(it, i) in lsl6Op"
                      :key="i"
                      :label="it.label"
                      :value="it.value"
                    ></el-option> </el-select
                ></span>
                <span style="margin: 0 10px; font-size: 14px">{{ v.un }}</span>
                <span
                  ><el-select
                    size="mini"
                    :placeholder="``"
                    v-model="v.rightOp"
                    @change="changeRightOp($event, index, idx1)"
                    style="width: 60px"
                  >
                    <el-option
                      v-for="(it, i) in lsl6Op"
                      :key="i"
                      :label="it.label"
                      :value="it.value"
                    ></el-option> </el-select
                ></span>

                <span
                  ><el-input
                    :disabled="v.rightOp == 'NO'"
                    size="mini"
                    v-model="v.rightValue"
                    style="width: 100px"
                  ></el-input
                ></span>
              </div>
            </el-form-item>
            <el-form-item>
              <div
                style="display: flex; align-items: center"
                v-if="item.nextQuestionId && (form.type == 2 || form.type == 3)"
              >
                <div>选项关联的问题是：</div>
                <div>{{ item.nextQuestionLabel }}</div>
                <i
                  type="primary"
                  class="el-icon-delete"
                  style="margin-left: 10px;cursor: pointer; color: #409eff"
                  @click="
                    form.options[index].nextQuestionId = '';
                    form.options[index].nextQuestionLabel = '';
                  "
                >
                  删除关联</i
                >
              </div>
            </el-form-item>
          </div>
          <!--          <el-form-item label="排序：">-->
          <!--            <el-input-number-->
          <!--              clearable-->
          <!--              :min="0"-->
          <!--              style="width: 200px"-->
          <!--              v-model="form.sort"-->
          <!--            ></el-input-number>-->
          <!--          </el-form-item>-->
          <el-form-item label="备注：" prop="note">
            <el-input
              type="textarea"
              show-word-limit
              clearable
              style="width: 400px"
              v-model="form.note"
              maxlength="200"
            ></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitForm('form')"
              >提交</el-button
            >
            <el-button @click="resetForm('form')">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-drawer>

    <el-dialog
      :visible.sync="dialogVisible"
      :title="'选择子问题'"
      width="600px"
    >
      <div style="display: flex; align-items: center">
        <div style="margin-right: 20px">请选择</div>
        <el-select
          clearable
          filterable
          placeholder="请选择关联问题"
          style="width: 450px"
          v-model="selectChildId"
        >
          <el-option
            v-for="item in secondQuestionList"
            :key="item.id"
            :label="item.label"
            :value="item.id"
          ></el-option>
        </el-select>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button size="mini" @click="onCancle()">取 消</el-button>
        <el-button size="mini" type="primary" @click="onSubmit()"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>
<script>
import {
  getProductDimension,
  addMatchingQuestion,
  getMatchingQuestionDetail,
  editMatchingQuestion,
  getSecondaryQuestionList
} from "@/api/product";
import log from "../../administration/log.vue";
export default {
  name: "addQuestion",
  props: {
    matchTypeList: {
      type: Array,
      default: () => {
        return [];
      }
    }
  },
  data() {
    return {
      drawer: false,
      direction: "rtl",
      ProductDimensionList: [],
      detailInfo: {},
      form: {
        matchType: [], // 多
        conditions: "", // 条件ID
        label: "",
        type: 2,
        metaId: "",
        must: 1, //1必填，0:选填
        sort: 0,
        note: "", // 备注
        firstShow: true,
        conditionsType: "",
        options: [
          {
            label: "", //提干
            value: null, //选项
            nextQuestionId: "",
            nextQuestionLabel: ""
          }
        ]
      },
      rules: {
        matchType: [
          { required: true, message: "请选择产品类型", trigger: "change" }
        ],
        conditions: [
          { required: true, message: "请选择条件", trigger: "change" }
        ],
        label: [{ required: true, message: "请输入题目", trigger: "blur" }],
        type: [
          { required: true, message: "请选择题目类型", trigger: "change" }
        ],
        must: [
          { required: true, message: "请选择是否必填", trigger: "change" }
        ],
        firstShow: [
          { required: true, message: "请选择是否主问题", trigger: "change" }
        ]
      },

      loading: false,
      secondQuestionList: [],
      dialogVisible: false,
      selectChildId: "",
      idx: null,
      lsl6List: [],
      lsl6Op: [
        { label: "无", value: "NO" },
        { label: "=", value: "EQ" },
        { label: "<", value: "LT" },
        { label: "<=", value: "LE" }
      ]
    };
  },
  methods: {
    changeLeftOp(e, idx, i) {
      if (e === "NO") {
        this.form.options[idx].value[i].leftValue = null;
      }
    },
    changeRightOp(e, idx, i) {
      if (e === "NO") {
        this.form.options[idx].value[i].rightValue = null;
      }
    },
    addQuesTionItem(item) {
      console.log(item);
      if (
        this.form.conditionsType === "OP_EQUAL" ||
        this.form.conditionsType === "OP_SCOPE"
      ) {
        const obj = JSON.parse(JSON.stringify(item.value));
        console.log(obj);
        obj.forEach(v => {
          v.leftValue = null;
          v.rightValue = null;
          v.rightOp = null;
          v.leftOp = null;
        });
        this.form.options.push({
          label: "",
          value: obj,
          nextQuestionId: "",
          nextQuestionLabel: ""
        });
      } else {
        this.form.options.push({
          label: "",
          value: [],
          nextQuestionId: "",
          nextQuestionLabel: ""
        });
      }
    },

    getSecondaryQuestionList(e) {
      const obj = this.ProductDimensionList.find(v => {
        return v.value === e;
      });

      console.log("obj", obj.valueType);
      if (obj.valueType !== "OP_EQUAL" || obj.valueType !== "OP_EQUAL") {
        this.form.options = [
          {
            label: "", //提干
            value: null, //选项
            nextQuestionId: "",
            nextQuestionLabel: ""
          }
        ];
      }
      this.form.metaId = "";
      this.form.conditionsType = obj.valueType;
      this.lsl6List = obj.selectList;
    },
    selectChild(e) {
      this.form.options.forEach(v => {
        v.value = null;
      });
      let arr = this.lsl6List
        .find(item => {
          return item.id === e;
        })
        .unknowns.split(",");

      const val = arr.map(v => {
        return {
          leftOp: "",
          leftValue: "",
          rightOp: "",
          rightValue: "",
          un: v
        };
      });
      this.form.options[0].value = val;
      this.form.options = this.form.options.slice(0, 1);
    },
    onCancle() {
      this.selectChildId = "";
      this.dialogVisible = false;
    },
    onSubmit() {
      if (!this.selectChildId) {
        return this.$message.error("请选择子问题");
      }
      this.dialogVisible = false;
      const obj = this.secondQuestionList.find(item => {
        return item.id == this.selectChildId;
      });
      this.form.options[this.idx].nextQuestionId = obj.id;
      this.form.options[this.idx].nextQuestionLabel = obj.label;
      this.selectChildId = "";
    },
    addChildQuestion(idx) {
      this.dialogVisible = true;
      this.idx = idx;
    },
    resetForm() {
      this.form = {
        matchType: [], // 多
        conditions: "", // 条件ID
        label: "",
        type: 2,
        must: 1, //1必填，0:选填
        sort: 0,
        note: "", // 备注
        firstShow: true,
        options: [
          {
            label: "", //提干
            value: null, //选项
            nextQuestionId: "",
            nextQuestionLabel: ""
          }
        ]
      };
      this.$refs.form.resetFields();
    },
    submitForm(form) {
      this.$refs[form].validate(valid => {
        if (valid) {
          const obj = Object.assign({}, this.form);

          if (
            obj.conditionsType == "OP_EQUAL" ||
            obj.conditionsType == "OP_SCOPE"
          ) {
            obj.options.forEach(v => {
              v.value = JSON.stringify(v.value);
            });
          }
          delete obj.conditionsType;
          if (obj.type == 1) {
            obj.options = [];
          }
          obj.matchType = obj.matchType.join(",");
          if (this.detailInfo.id) {
            editMatchingQuestion(obj).then(res => {
              this.$message.success("修改成功");
              this.drawer = false;
              this.resetForm();
              setTimeout(() => {
                this.$emit("getList");
              }, 500);
            });
          } else {
            addMatchingQuestion(obj).then(res => {
              this.$message.success("添加成功");
              this.drawer = false;
              setTimeout(() => {
                this.$emit("getList");
                this.resetForm();
              }, 500);
            });
          }
        }
      });
    },
    handleClose() {
      this.drawer = false;
      setTimeout(() => {
        this.resetForm();
      }, 500);
    },
    getSecondQuestionList() {
      getSecondaryQuestionList().then(res => {
        this.secondQuestionList = res.data;
      });
    },
    conditionsType(conditions) {
      let type = "";
      if (conditions) {
        this.ProductDimensionList.forEach(v => {
          if (v.value == conditions) {
            type = v.valueType;
            this.lsl6List = v.selectList;
          }
        });
      }
      return type;
    },
    getDetail() {
      getMatchingQuestionDetail(this.detailInfo.id)
        .then(async res => {
          res.data.matchType = res.data.matchType.split(",");
          res.data.conditionsType = await this.conditionsType(
            res.data.conditions
          );
          if (res.data.options.length < 0) {
            res.data.options = [
              {
                label: "",
                value: [],
                nextQuestionId: "",
                nextQuestionLabel: ""
              }
            ];
          }

          if (res.data.options.length > 0) {
            if (
              res.data.conditionsType == "OP_EQUAL" ||
              res.data.conditionsType == "OP_SCOPE"
            ) {
              res.data.options.forEach(v => {
                v.value = JSON.parse(v.value);
              });
            }
          }
          // console.log(res.data.conditions, this.ProductDimensionList);
          // // this.lsl6List = this.ProductDimensionList.find(v => {
          // //   return v.value == res.data.conditions;
          // // }).selectList;

          this.form = Object.assign({}, res.data);
          this.loading = false;
        })
        .finally(() => {
          this.loading = false;
        });
    },
    async showDrawer(v) {
      getProductDimension().then(res => {
        this.ProductDimensionList = res.data.map(v => {
          return {
            value: v.conditions,
            label: v.conditionsName,
            selectList: v.selectList,
            valueType: v.valueType
          };
        });
      });
      await this.getSecondQuestionList();
      if (v) {
        this.detailInfo = v;
        this.loading = true;
        setTimeout(() => {
          this.getDetail();
        }, 500);
      }

      this.drawer = true;
    }
  }
};
</script>

<style scoped lang="scss"></style>
